package com.antdant.handle;

import com.antdant.common.GeneralCode;
import com.antdant.common.GeneralResponse;
import com.antdant.exception.GeneralException;
import com.antdant.exception.NeedLoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Lee Yunc
 * @Date 2021/2/24 17:26
 * @Description: 全局异常拦截
 * @Version 1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandle {

    @ResponseBody
    @ExceptionHandler(value = NeedLoginException.class)
    public GeneralResponse needLoginExceptionHandle(HttpServletRequest request, HttpServletResponse response, Exception e) {
        if (e instanceof NeedLoginException) {
            log.error("{} 需要登录,Error:", request.getRequestURI(), e);
            NeedLoginException exp = (NeedLoginException) e;
            return GeneralResponse.failed(exp.getCode(), e.getMessage());
        }
        return GeneralResponse.failed(GeneralCode.NEED_LOGIN, "需要重新登录，请登录！");
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public GeneralResponse globalExceptionHandle(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("request uri:{} raise exception,Error:", request.getRequestURI(), e);
        if (e instanceof GeneralException) {
            GeneralException exp = (GeneralException) e;
            return GeneralResponse.failed(exp.getCode(), e.getMessage());
        }
        return GeneralResponse.failed("服务器开小差了，请稍后重试！");
    }

}
